package com.example.learnspring.filter;


import com.example.learnspring.exception.BusinessException;
import com.example.learnspring.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletComponentScan;

import java.io.IOException;

@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String token = req.getHeader("Authorization");

        String uri = req.getRequestURI();

        if(uri.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);

            // 返回结束这个请求
            return;
        }

        if(token==null){
            resp.setStatus(401);
            log.info("未登录");
            return;
        }

        try{
            Claims claims = JwtUtil.getClaimsFromToken(token);
            log.info("claims={}",claims);
        } catch (Exception e) {
            resp.setStatus(401);
            return;
//            throw new RuntimeException(e);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
